﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BridgeManager
{
    class BridgeManager
    {
        private PortPairs portPairDict = new PortPairs();

        public List<BridgeInfo> GetBridgeList()
        {
            BridgeInfo bridgeInfo = new BridgeInfo();
            bridgeInfo.action = "query";

            byte[] data = Encoding.Default.GetBytes(JsonConvert.SerializeObject(bridgeInfo));
            string content = InOutService(data, data.Length);

            StringReader sr = new StringReader(content);

            JsonSerializer serializer = new JsonSerializer();
            object obj = serializer.Deserialize(new JsonTextReader(sr), typeof(List<BridgeInfo>));
            List<BridgeInfo> bridgeList = obj as List<BridgeInfo>;
            if (bridgeList == null)
                bridgeList =  new List<BridgeInfo>();

            /* 更新成员 */
            List<BridgeInfo> bridgeInfoList = new List<BridgeInfo>();
            for (int i = 0; i < bridgeList.Count; i++)
            {
                BridgeInfo bridge = bridgeList[i];

                string pairNum = bridge.comBName.Substring(4);
                if (portPairDict.ContainsKey(pairNum))
                {
                    PortPair portPair = portPairDict[pairNum];
                    if (portPair.portA.ContainsKey("realportname"))
                    {
                        bridge.comAName = portPair.portA["realportname"];
                        bridgeInfoList.Add(bridge);
                    }
                }
            }

            return bridgeInfoList;
        }

        public string CreateBridge(BridgeInfo bridge)
        {
            /* 添加串口对 */
            PortPair pair = portPairDict.CreatePortPair();
            bridge.comAName = pair.portA["realportname"];
            bridge.comBName = string.Format("CNCB{0}", pair.GetNum());

            /* 通知服务 */
            bridge.action = "add";
            byte[] data = Encoding.Default.GetBytes(JsonConvert.SerializeObject(bridge));
            InOutService(data, data.Length);

            return bridge.comAName;
        }

        public BridgeInfo GetBridgeInfoByName(string comName)
        {
            List<BridgeInfo> bridgeInfoList = GetBridgeList();
            for (int i = 0; i < bridgeInfoList.Count; i++)
            {
                BridgeInfo bridgeInfo = bridgeInfoList[i];
                if (bridgeInfo.comAName == comName)
                    return bridgeInfo;
            }

            return new BridgeInfo();
        }

        public bool DeleteBridgeByName(string comName)
        {
            List<BridgeInfo> bridgeInfoList = GetBridgeList();
            for (int i = 0; i < bridgeInfoList.Count; i++)
            {
                BridgeInfo bridgeInfo = bridgeInfoList[i];
                if (bridgeInfo.comAName == comName)
                {
                    bridgeInfo.action = "remove";
                    byte[] data = Encoding.Default.GetBytes(JsonConvert.SerializeObject(bridgeInfo));
                    string content = InOutService(data, data.Length);

                    portPairDict.RemovePair(comName);

                    break;
                }
            }

            return true;
        }

        private string InOutService(byte[] data, int len)
        {
            string content;
            using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "mynamedpipe", PipeDirection.InOut))
            {
                pipeClient.Connect();
                pipeClient.Flush();

                pipeClient.Write(data, 0, len);
                using (StreamReader sr = new StreamReader(pipeClient))
                {
                    content = sr.ReadToEnd();
                }
                pipeClient.Close();
            }

            return content;
        }
    }
}
